package com.czd.support.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.czd.base.model.JsonResult;
import com.czd.base.utils.TextUtil;
import com.czd.base.utils.WebUtils;
import com.czd.support.common.Configuration;
import com.czd.support.enums.CodeEnum;
import com.czd.support.enums.CodeTypeEnum;
import com.czd.support.enums.RegisterTypeEnum;
import com.czd.support.model.PhoneCode;
import com.czd.support.model.Question2;
import com.czd.support.model.User;
import com.czd.support.model.Warning;
import com.czd.support.service.AnswerService;
import com.czd.support.service.ChannelService;
import com.czd.support.service.ContentService;
import com.czd.support.service.PhonecodeService;
import com.czd.support.service.PhrasebookService;
import com.czd.support.service.QuestionService;
import com.czd.support.service.RoomService;
import com.czd.support.service.UserService;
import com.czd.support.service.VideoService;
import com.czd.support.service.WarningService;
import com.czd.support.service.ZcncNewsService;
import com.czd.support.util.DateFormatUtil;
import com.czd.support.util.MD5Utils;
import com.czd.support.util.PhoneUtils;
import com.czd.support.util.SMSUtil;
import com.czd.support.util.VerifyCodeUtils;

/**
 * Created with IntelliJ IDEA.
 * Author: Jerry.hu
 * Create: Jerry.hu (2014-10-03 23:53)
 * Description:
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/api")
public class ApiController extends BaseController{
	private static Log log = LogFactory.getLog(ApiController.class);

    @Autowired
    private QuestionService questionService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private AnswerService answerService;
    @Autowired
    private PhrasebookService phrasebookService;
    @Autowired
    private ContentService contentService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private UserService userService;
    @Autowired
    private PhonecodeService phonecodeService;
    @Autowired
    private ZcncNewsService zcncNewsService;
    @Autowired
    private WarningService warningService;
    

    @RequestMapping(value = "/query/qa")
    @ResponseBody
    public JsonResult queryQA(){
        return JsonResult.OK.put("qa",questionService.queryAllQA());
    }

    @RequestMapping(value = "/answers/autocomplete/{key}")
    @ResponseBody
    public JsonResult queryQuestion(@PathVariable String key){
        try {
            return JsonResult.OK.put("answers", answerService.autocompleteById(Integer.parseInt(key)));
        }catch (Exception e){
            return  JsonResult.OK.put("answers", answerService.autocompleteByName(key));
        }
    }

    @RequestMapping(value = "/answers/check/{id}")
    @ResponseBody
    public JsonResult checkAnswer(@PathVariable int id){
       if(answerService.findById(id) != null){
           return JsonResult.OK;
       }
       return JsonResult.FAIL;
    }

    @RequestMapping(value = "/room/autocomplete/{key}")
    @ResponseBody
    public JsonResult querRoom(@PathVariable String key){
        try {
            return JsonResult.OK.put("rooms",roomService.autocompleteById(Integer.parseInt(key)));
        }catch (Exception e){
            return  JsonResult.OK.put("rooms",roomService.autocompleteByName(key));
        }
    }

    @RequestMapping(value = "/room/check/{id}")
    @ResponseBody
    public JsonResult checkRoom(@PathVariable int id){
        if(roomService.findById(id) != null){
            return JsonResult.OK;
        }
        return JsonResult.FAIL;
    }

    @RequestMapping(value = "/query/{roomId}/qa")
    @ResponseBody
    public JsonResult queryRoomQA(@PathVariable int roomId){
        return JsonResult.OK.put("roomQa",questionService.queryQAByRoomId(roomId));
    }

    @RequestMapping(value = "/query/phrasebook/{code}")
    @ResponseBody
    public JsonResult queryPhrasebooksByCode(@PathVariable String code){
        return JsonResult.OK.put("phrasebooks",phrasebookService.getPhrasebooks(code));
    }

    @RequestMapping(value = "/qa/{roomId}/add",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addQq(@PathVariable int roomId,Question2 question){
        if(question != null){
            question.setRoomId(roomId);
            if(questionService.insert(question)){
                return JsonResult.OK.put("qId",question.getId());
            }
        }
        return JsonResult.FAIL;
    }

    @RequestMapping(value = "/qa/{id}/delete",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult delete(@PathVariable int id){
        Question2 question = questionService.findById(id);
        if(question != null){
            if(questionService.deleteById(id)){
                return JsonResult.OK;
            }else {
                return JsonResult.FAIL.put("msg","删除题目失败");
            }
        }
        return JsonResult.FAIL.put("msg","题目已经不存在");
    }


    @RequestMapping(value = "/qa/{id}/edit",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult edit(@PathVariable int id){
        Question2 question = questionService.findById(id);
        if(question != null){
            return JsonResult.OK.put("qa",question);
        }
        return JsonResult.FAIL.put("msg","题目已经不存在");
    }


    @RequestMapping(value = "/qa/{id}/edit",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult update(@PathVariable int id,Question2 question){
        Question2 question2 = questionService.findById(id);
        if(question2 != null){
            question.setId(id);
            if(questionService.update(question)){
                return JsonResult.OK.put("qId",id);
            }else {
                return JsonResult.FAIL.put("msg","删除题目失败");
            }
        }
        return JsonResult.FAIL.put("msg","题目已经不存在");
    }
    
    /**
     * 查询所有新闻
     * @return
     */
    @RequestMapping(value="/queryContents")
    @ResponseBody
    public JsonResult queryContents(){
    	return JsonResult.OK.put("contents", contentService.selectList("queryContens"));
    }

    /**
     * 所属栏目新闻列表
     * @param code
     * @return
     */
    @RequestMapping(value="/queryContentsByCode")
    @ResponseBody
    public JsonResult queryContentsByCode(int code){
    	//code = 11304;
    	if(contentService.queryByCode(code).size()>0){
    		return JsonResult.OK.put("contents", contentService.queryByCode(code));
    	}
    	return JsonResult.FAIL.put("msg","内容不存在");
    }
    
    /**
     * 新闻栏目
     * @return
     */
    @RequestMapping(value="/getContentChannels")
    @ResponseBody
    public JsonResult getContentChannels(){
    	return JsonResult.OK.put("contentChannels", channelService.getContentChannels());
    }

    /**
     * 视频文件
     * @return
     */
    @RequestMapping(value="/getVideos")
    @ResponseBody
	public JsonResult getVideos(){
		if(videoService.getVideos().size()>0){
			return JsonResult.OK.put("videos", videoService.getVideos());
		}
    	return JsonResult.FAIL.put("msg", "视频文件不存在");
	}
    
    /**
     * 登陆接口
     * @param phone
     * @param password
     * @return
     */
    @RequestMapping(value="/login")
    @ResponseBody
    public JsonResult login(HttpServletRequest request,User user){
    	String mobilePhone = WebUtils.findParamStr(request,"mobilePhone","");
    	String password = MD5Utils.str2Md5(WebUtils.findParamStr(request,"password",""));
    	log.info("手机号："+mobilePhone+"，密码："+WebUtils.findParamStr(request,"password",""));
    	user = userService.login(mobilePhone, password);
    	if(userService.login(mobilePhone, password) != null){
    		return JsonResult.OK.put("user", user);
    	}
    	return JsonResult.FAIL.put("msg", "登陆失败，用户名或密码错误");
    }
    
    /**
	 * 发送验证码信息
	 * @param request
	 */
	@RequestMapping(value = "/sendSms")
	@ResponseBody
	public JsonResult sendSMS(HttpServletRequest request,PhoneCode phoneCode){
		String mobilePhone = WebUtils.findParamStr(request,"mobilePhone","");
		if(StringUtils.isNotBlank(mobilePhone) && PhoneUtils.isMobile(mobilePhone)){
			Configuration configuration = Configuration.getInstance();
			//短信验证码
			String code = VerifyCodeUtils.runVerifyCode(4, CodeTypeEnum.数字);
			log.info("验证码："+code);
			String content = TextUtil.format(configuration.getSms_code_content(),CodeEnum.注册.toString(), code);
			if(SMSUtil.sendMessage1(mobilePhone,content)){
				phoneCode.setMobilePhone(mobilePhone);
				phoneCode.setCode(code);
				if(phonecodeService.findByMobilePhone(mobilePhone)!=null){
					phonecodeService.update(phoneCode);
				}else{
					phonecodeService.insert(phoneCode);
				}
				return JsonResult.OK.put("code", code);
			}
		}
		return JsonResult.FAIL.put("msg", "发送短信验证码失败");
	}
    
    /**
     * 注册接口
     * @param phone
     * @return
     */
	@RequestMapping(value="/register")
	@ResponseBody
    public JsonResult register(HttpServletRequest request,User user){
    	String mobilePhone = WebUtils.findParamStr(request,"mobilePhone",""); //手机号 
    	String password = MD5Utils.str2Md5(WebUtils.findParamStr(request,"password","")); //密码 
    	String code = WebUtils.findParamStr(request,"code",""); //短信验证码
    	PhoneCode phoneCode=phonecodeService.findByMobilePhone(mobilePhone);
		if (!code.equals(phoneCode.getCode())) {
			return JsonResult.FAIL.put("msg", "对不起，验证码不正确");
		} else if ((System.currentTimeMillis()-phoneCode.getSendTime().getTime())/60000>30) {
			return JsonResult.FAIL.put("msg", "对不起，验证码失效");
		}
		user.setMobilePhone(mobilePhone);
		user.setPassword(password);
		user.setStatus(0);
		user.setRegisterType(RegisterTypeEnum.手机号码.ordinal());
		user.setNickName(mobilePhone);
		if(userService.register(user)){
			return JsonResult.OK.put("msg", "注册成功");
		}
		return JsonResult.FAIL.put("msg", "注册失败");
    }
	
	/**
	 * 忘记密码
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/resetPassword")
	@ResponseBody
	public JsonResult resetPassword(HttpServletRequest request,User user,PhoneCode phoneCode){
		String mobilePhone = WebUtils.findParamStr(request,"mobilePhone","");
		String code = WebUtils.findParamStr(request,"code","");
		String password = MD5Utils.str2Md5(WebUtils.findParamStr(request, "password",""));
		log.info("mobilePhone："+mobilePhone+"，code："+code+"，+password："+password);
		user = userService.findByAccountCode(mobilePhone);
		phoneCode = phonecodeService.findByMobilePhone(mobilePhone);
		if(user==null){
			return JsonResult.FAIL.put("msg", "该手机号暂未注册");
		}else{
			if(code.equals(phoneCode.getCode())&&(System.currentTimeMillis()-phoneCode.getSendTime().getTime())/60000<30){
				user.setPassword(MD5Utils.str2Md5(password));
				userService.modifyPwd(user.getId(), password);
				return JsonResult.OK.put("msg", "密码修改成功");
			}else{
				return JsonResult.FAIL.put("msg", "密码修改失败");
			}
		}
	}
	
	/**
	 * 修改密码
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/modifyPwd")
	@ResponseBody
	public JsonResult modifyPwd(HttpServletRequest request,User user){
		String mobilePhone = WebUtils.findParamStr(request, "mobilePhone", "");
		user = userService.findByAccountCode(mobilePhone);
		String password = MD5Utils.str2Md5(WebUtils.findParamStr(request, "password", "")); //新密码
		String password2 = MD5Utils.str2Md5(WebUtils.findParamStr(request,"password2",""));	//确认密码
		String oldPwd = MD5Utils.str2Md5(WebUtils.findParamStr(request,"oldPwd","")); //原始密码
		if(!oldPwd.equals(user.getPassword())){
			return JsonResult.FAIL.message("对不起，当前密码填写错误");
		}else if(password.equals(user.getPassword())){
			return JsonResult.FAIL.message("对不起，新密码和原始密码不能一致");
		}else if(!password.equals(password2)){
			return JsonResult.FAIL.message("两次填写的新密码不一致，请确认后重新填写");
		}else {
			if(userService.modifyPwd(user.getId(),password)){
				return JsonResult.OK.put("msg", "修改密码成功");
			}
		}
		return JsonResult.FAIL.message("修改密码失败");
	}
	
	/**
	 * 验证手机号是否已注册过
	 * @return
	 */
	@RequestMapping(value="/checkIsRegister")
	@ResponseBody
	public JsonResult checkIsRegister(HttpServletRequest request,User user){
		String mobilePhone = WebUtils.findParamStr(request,"mobilePhone","");
		if(userService.findByAccountCode(mobilePhone)==null){
			return JsonResult.OK.put("msg", "该手机号可以使用");
		}
		return JsonResult.FAIL.put("msg", "该手机号已被注册");
	}
	
	/**
	 * 中财内参咨询新闻
	 * @return
	 */
	@RequestMapping(value="/queryZcncNews")
	@ResponseBody
	public JsonResult queryZcncNews(){
		if(zcncNewsService.queryZcncNews().size()>0){
			return JsonResult.OK.put("news", zcncNewsService.queryZcncNews());
		}
		return JsonResult.FAIL.put("msg", "暂无数据");
	}
	
	/**
	 * 添加预警
	 * @param request
	 * @param warning
	 * @return
	 */
	@RequestMapping(value="/insertWarning")
	@ResponseBody
	public JsonResult insertWarning(HttpServletRequest request, Warning warning){
		Warning warningCheck = warningService.findBySymbolUserId(warning);
		if(warningCheck == null){
			warning.setIsAdd(1);
			if(warningService.insert(warning)){
				return JsonResult.OK.put("msg", "添加预警成功");
			}
			return JsonResult.FAIL.put("msg", "添加预警失败");
		}else{
			warningCheck.setRisingPrice(warning.getRisingPrice());
			warningCheck.setFallPrice(warning.getFallPrice());
			warningCheck.setIsRemind(0);
			if(warningService.updatePrices(warningCheck)){
				return JsonResult.OK.put("msg", "修改预警成功");
			}
			return JsonResult.FAIL.put("msg", "修改预警失败");
		}
	}
	
	/**
	 * 查看用户添加的预警记录
	 * @param request
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/findUserWarnings")
	@ResponseBody
	public JsonResult findUserWarnings(HttpServletRequest request, int userId){
		List<Warning> list = warningService.findByUserId(userId);
		if(list.size()>0){
			return JsonResult.OK.put("warnings", list);
		}
		return JsonResult.FAIL.put("warnings", null);
	}
	
	/**
	 * 预警删除
	 * @param warning
	 * @return
	 */
	@RequestMapping(value="/delWarnings")
	@ResponseBody
	public JsonResult delWarnings(Warning warning){
		if(warningService.delWarnings(warning)){
			return JsonResult.OK.put("msg", "删除预警成功");
		}
		return JsonResult.FAIL.put("msg", "删除预警失败");
	}
	
	/**
	 * 修改预警状态值为已预警
	 * @param warning
	 * @return
	 */
	@RequestMapping(value="/updateIsdRemind")
	@ResponseBody
	public JsonResult updateIsdRemind(Warning warning){
		warning.setIsRemind(1);
		if(warningService.updateIsdRemind(warning)){
			return JsonResult.OK.put("msg", "修改预警状态成功");
		}
		return JsonResult.FAIL.put("msg", "修改预警状态失败");
	}
	
	public static void main(String[] args) {
		Date date = DateFormatUtil.getDate("2015-05-21 15:06:14");
		System.out.println((System.currentTimeMillis()-date.getTime())/60000);
	}
	
}
